package com.aistudy.file.config;

import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.SetBucketPolicyArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * Minio初始化器，用于创建存储桶
 * 
 * @author aistudy
 */
@Slf4j
@Component
public class MinioInitializer implements CommandLineRunner {

    @Autowired
    private MinioClient minioClient;
    
    @Autowired
    private MinioConfig minioConfig;

    @Override
    public void run(String... args) {
        try {
            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(
                    BucketExistsArgs.builder()
                            .bucket(minioConfig.getBucketName())
                            .build());
            
            if (!isExist) {
                // 创建存储桶
                minioClient.makeBucket(
                        MakeBucketArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .build());
                
                // 设置存储桶访问策略为公共读
                String policy = "{\n" +
                        "    \"Version\": \"2012-10-17\",\n" +
                        "    \"Statement\": [\n" +
                        "        {\n" +
                        "            \"Effect\": \"Allow\",\n" +
                        "            \"Principal\": \"*\",\n" +
                        "            \"Action\": \"s3:GetObject\",\n" +
                        "            \"Resource\": \"arn:aws:s3:::" + minioConfig.getBucketName() + "/*\"\n" +
                        "        }\n" +
                        "    ]\n" +
                        "}";
                
                minioClient.setBucketPolicy(
                        SetBucketPolicyArgs.builder()
                                .bucket(minioConfig.getBucketName())
                                .config(policy)
                                .build());
                
                log.info("成功创建Minio存储桶: {}", minioConfig.getBucketName());
            } else {
                log.info("Minio存储桶已存在: {}", minioConfig.getBucketName());
            }
        } catch (Exception e) {
            log.error("初始化Minio存储桶失败", e);
        }
    }
} 